package com.bjpowernode.crm.web.controller;

import com.bjpowernode.crm.pojo.Type;
import com.bjpowernode.crm.service.TypeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @GetMapping("index.html")
    public ModelAndView index(ModelAndView mv) {
        mv.addObject("types", typeService.getAll());
        mv.setViewName("settings/dictionary/type/index");
        return mv;
    }

    @PostMapping("save.do")
    public String save(Type type) {
        typeService.save(type);

        return "redirect:/type/index.html";
    }

    @GetMapping("check.do")
    @ResponseBody
    public Map check(String id) {
        return new HashMap(){{
            put("repeat", typeService.get(id) != null);
        }};
    }

    @GetMapping("edit.html")
    public ModelAndView edit(String id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("type", typeService.get(id));
        mv.setViewName("settings/dictionary/type/edit");
        return mv;
    }

    @PostMapping("edit.do")
    public String edit(Type type) {
        typeService.edit(type);
        return "redirect:/type/index.html";
    }

    @GetMapping("checkDel.do")
    // id=1,2,3  or id=1&id=2&id=3
    @ResponseBody
    public List checkDel(String[] id) {
        return typeService.getRel(id);
    }

    @GetMapping("del.do")
    public String del(String[] id) {
        typeService.del(id);
        return "redirect:/type/index.html";
    }

    @GetMapping("delForce.do")
    public String delForce(String[] id) {
        typeService.delForce(id);
        return "redirect:/type/index.html";
    }

    @GetMapping("types.json")
    @ResponseBody
    public List types() {
        return typeService.getAll();
    }
}
